package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.UserDao;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null){
            return null;
        }
        return user;
    }

    @Override
    public Result updatepassword(String currentPassword, String newPassword, String username) {
        try {
            //根据用户名和密码查询数据库
            User user = userDao.findByUser(username);
            if (user==null){
                return new Result(false,"当前用户名存在正确");
            }
            //获取密码
            String password = user.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            //判断密码是否正确
            boolean flag = encoder.matches(currentPassword, password);
            if (!flag){
                return new Result(false,"当前密码输入不正确");
            }
            //修改密码
            userDao.updatePasswordByUsername(username,newPassword);
            return new Result(true,"密码修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"密码修改失败");
        }
    }

    @Override
    public Result updateByName(String checkName, String encode) {
        try {
            userDao.updatePasswordByUsernameOrTelephone(checkName,encode);
            return new Result(true,"修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改失败");
        }
    }
}
